package com.tcr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

import org.apache.log4j.Logger;

import com.tcr.common.TcCov;

public class CoverageDao {

	@SuppressWarnings("finally")
	public final static boolean add_cov(int pid, String c_dir,
			String c_version, int uid) {
		Connection conn = null;
		boolean b = false;
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn.prepareStatement(SqlString.add_cov);
			ps.setInt(1, pid);
			ps.setString(2, c_dir);
			ps.setString(3, c_version);
			ps.setInt(4, uid);
			int res = ps.executeUpdate();
			b = (res != 0);
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return b;
		}

	}

	@SuppressWarnings("finally")
	public static List<TcCov> getCovByPid(int pid) {
		Connection conn = null;
		List<TcCov> covs = new ArrayList<TcCov>();
		try {
			conn = dbutil.pool.getConnection();
			PreparedStatement ps = conn
					.prepareStatement(SqlString.get_cov_by_pid);
			ps.setInt(1, pid);
			ResultSet res = ps.executeQuery();
			while (res.next()) {
				String c_dir = res.getString(1);
				String c_verson = res.getString(2);
				int uid = res.getInt(3);
				Timestamp upload_time = res.getTimestamp(4);

				covs.add(new TcCov(c_dir, upload_time, c_verson, uid));
			}
		} catch (Exception ex) {
			logger.error(ex);
		} finally {
			if (conn != null)
				dbutil.pool.backConn(conn);
			return covs;
		}
	}

	private final static Logger logger = Logger.getLogger(CoverageDao.class);
	private final static DbUtil dbutil = DbUtil.getInstance();
}
